<?php
namespace app\admin\model;

class DepartmentModel extends BaseModel
{
    // 确定链接表名
    protected $name = 'department';

    /**
     * 获取部门数据
     */
    public function getDepartmentInfo($id)
    {
        $result = $this->field('id,name,pid')->select();
        $str = '';

        $role = new RoleModel();
        $rule = $role->getRuleById($id);

        if(!empty($rule)){
            $rule = explode(',', $rule);
        }

        foreach($result as $key=>$vo){
            $str .= '{ "id": "' . $vo['id'] . '", "pId":"' . $vo['pid'] . '", "name":"' . $vo['name'].'"';

            if(!empty($rule) && in_array($vo['id'], $rule)){
                $str .= ' ,"checked":1';
            }

            $str .= '},';

        }

        return '[' . rtrim($str, ',') . ']';
    }

    /**
     * 获取部门数据
     * @return mixed
     */
    public function getDepartmentList()
    {
        return $this->where($this->departIn("id"))->select()->toArray();
    }

    /**
     * 插入部门信息
     * @param $param
     */
    public function insertDepart($param)
    {
        try{

            $this->save($param);
            return msg(1, '', '添加部门成功');
        }catch(PDOException $e){

            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 编辑部门
     * @param $param
     */
    public function editDepart($param)
    {
        try{

            $this->save($param, ['id' => $param['id']]);
            return msg(1, '', '编辑部门成功');
        }catch(PDOException $e){

            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 删除部门
     * @param $id
     */
    public function delDepart($id)
    {
        try{

            $this->where('id', $id)->delete();
            return msg(1, '', '删除部门成功');

        }catch(PDOException $e){
            return msg(-1, '', $e->getMessage());
        }
    }

    /**
     * [获取所有子部门ID]
     */
    public function getSonsByPid($id){
        $arr = [];
        $lower = $this->where('pid',$id)->column('id');
        foreach($lower as $v){
            $arr[] = $v;
			$arr[] = $this->getSonsByPid($v);
        }
        $arr = changeArrTo1D($arr);
        return $arr;
    }
}
